﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ComponentModel.Composition.Hosting;
using System.ServiceModel.Dispatcher;

namespace WCFMEFSample.Interface
{
    /// <summary>
    /// Define a service behavior (instantiating the instance via MEF)
    /// </summary>
    public class ExportServiceBehavior:IServiceBehavior
    {
        private readonly string _name;
        private readonly CompositionContainer _container;
        
        public ExportServiceBehavior(CompositionContainer container,string name)
        {
            if (container == null)
                throw new ArgumentNullException("container");

            _container = container;
            _name = name;
        }

        #region IServiceBehavior
        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints,BindingParameterCollection bindingParameters) { }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
            {
                foreach (var endpoint in channelDispatcher.Endpoints)
                {
                    endpoint.DispatchRuntime.InstanceProvider = new ExportInstanceProvider(_container, _name);
                }
            }
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { }
        #endregion
    }
}
